'use strict';

/* eslint-disable */
$(function () {
  function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
    return null;
  }
  function addParama (key, val, clear) {
    var search = window.location.search;
    var url = '';
    if (search.indexOf('?') != -1) {
      search = search.substring(1);
      var search_arr = search.split('&');
      var url_arr = [];
      var exists = 0;
      for (var i = 0; i < search_arr.length; i++) {
        if (!search_arr[i])
          continue;
        var temp = search_arr[i].split('=');
        if (key == temp[0]) {
          exists = 1;
          url_arr.push(key + '=' + val);
        } else {
          if (temp[0] != 'page' && temp[0] != 'token') {
            url_arr.push(search_arr[i]);
          }
        }
      }
      if (!exists)
        url_arr.push(key + '=' + val);
      if (clear) {
        var idx = url_arr.findIndex(function(item) {
          return item.indexOf(clear) !== -1;
        });
        if (idx !== -1) {
          url_arr.splice(idx, 1);
        }
      }
      url = window.location.pathname + '?' + url_arr.join('&');
    } else {
      url = window.location.pathname + '?' + key + '=' + val;
    }
    window.location.href = url;
  }

  var intro = $('#intro');
  var tan = $('#tan');
  var faculty = $('#faculty');
  var fellows = $('#fellows');
  var phd = $('#phd');
  var ms = $('#ms');
  var alumni = $('#alumni');

  intro.click(function() {
    addParama('name', 'intro', 'tid')
  });
  tan.click(function() {
    addParama('name', 'teacher', 'tid')
  });
  faculty.click(function() {
    addParama('name', 'faculty', 'tid')
  });
  fellows.click(function() {
    return;
  });
  phd.click(function() {
    addParama('name', 'phd', 'tid')
  });
  ms.click(function() {
    addParama('name', 'ms', 'tid')
  });
  alumni.click(function() {
    addParama('name', 'alumni', 'tid')
  });

  var name = getQueryString("name");
  var tid = getQueryString("tid");

  // 需要达到的效果，当出现tid的时候，说明是需要显示某教师的详情
  // 但点击其他栏目的时候 又需要把name更换 并同时需要去掉tid
  name = name ? name : 'intro';
  if (tid) {
    // 此时显示某教师的详情
    initMain(1);
    updateTeacherInfo(tid);
    return;
  }

  function initMain(index) {
    var arr = [
      '#lab-intro',
      '#lab-person__intro',
      '#lab-staff',
      '#lab-follows',
      '#lab-phd',
      '#lab-ms',
    ];
    $(arr[index]).show();
    for (var i = 0; i < arr.length; i++) {
      if (i !== index) {
        $(arr[i]).hide();
      }
    }
  }
  function updateTeacherInfo(tid) {
    var req = $.ajax({
      url: "http://39.106.171.39:8011/mbl/Teacher/getTeacherItem",
      method: "GET",
      data: {
        teacherid: tid,
      },
      dataType: "json",
    });
    req.done(function (data) {
      // basicinfo
      $('#teacher-img').attr('src', data.picture);
      $('#teacher-address').text(data.address);
      $('#teacher-contact').text(data.contact);
      $('#teacher-name').text(data.teachername);
      $('#teacher-biography').text(data.biography);
      // education
      var educationTimeline = $('#education-timeline');
      var educations = data.educations;
      for (var i = 0, len = educations.length; i < len; i++) {
        var liElem = $('<li></li>').append($('<div class="timeline-bullet"></div>'));
        var spanElemTime = $('<span class="timeline-item__time"></span>').text(educations[i].year);
        var spanElemTitle = $('<span class="timeline-item__title"></span>').text(educations[i].degree);
        var pElemTitle = $('<p class="timeline-item__txt"></p>').text(educations[i].school);
        liElem.append(spanElemTime).append(spanElemTitle).append(pElemTitle);
        educationTimeline.append(liElem);
      }
      // interest
      $('#teacher-interest').text(data.interest);
      // articles
      var teacherPublication = $('#teacher-publication');
      var lists = data.articles;
      for (i = 0; i < lists.length; i++) {
        var item = $('<section class="publication-item"></section>');
        var h3 = $('<h3></h3>').text(lists[i].title);
        var p1 = $('<p></p>').text(lists[i].author);
        var p2 = $('<p></p>');
        var journalName = $('<span></span>').text(lists[i].journalname);
        var doi = $('<span class="mark"></span>').text(lists[i].doi);
        p2.append(journalName).append(': DOI: ').append(doi);

        item.append(h3).append(p1).append(p2);
        teacherPublication.append(item);
      }
      // awards
      var tearcherAwards = $('#teacher-awards');
      var awards = data.awards;
      for (i = 0; i < awards.length; i++) {
        var liElemAwards = $('<li></li>').append($('<div class="timeline-bullet"></div>'));
        var spanElemTitleAwards = $('<span class="timeline-item__time"></span>').text(awards[i].year);
        var pElemTitleAwards = $('<p class="timeline-item__txt"></p>').text(awards[i].award);
        liElemAwards.append(spanElemTitleAwards).append(pElemTitleAwards);
        tearcherAwards.append(liElemAwards);
      }
    });
  }
  switch (name) {
    case 'intro': {
      initMain(0);
      // 请求实验室介绍接口
      break;
    }
    case 'teacher': {
      initMain(1);
      updateTeacherInfo('4641831526ae4f9d9b83b013908823e6');
      break;
    }
    case 'faculty': {
      initMain(2);
      var req = $.ajax({
        url: "http://39.106.171.39:8011/mbl/Teacher/getTeacherList",
        method: "GET",
        data: {
          page: 1,
          pagesize: 12,
        },
        dataType: "json",
      });
      req.done(function (data) {
        var facultyList = data.rows;
        var staffWrapper = $('#staff-wrapper');
        for (let i = 0, len = facultyList.length; i < len; i++) {
          var staff = $('<div class="staff pointer"></div>');
          var img = $('<img>').attr('src', facultyList[i].picture);
          var p = $('<p class="staff-name"></p>').text(facultyList[i].teachername);
          var span = $('<span class="staff-position"></span>').text(facultyList[i].role);

          staff.append(img).append(p).append(span);

          staff.click(function() {
            console.log('click ', i);
            addParama('tid', facultyList[i].teacherid);
          });
          staffWrapper.append(staff);
        }
      });
      break;
    }
    case 'phd': {
      initMain(4);
      var req = $.ajax({
        url: "http://39.106.171.39:8011/mbl/Student/getStudentList",
        method: "GET",
        data: {
          page: 1,
          pagesize: 12,
        },
        dataType: "json",
      });
      req.done(function (data) {
        // var facultyList = data.rows;
        var phds = data.rows || [];
        var years = [];
        phds = phds.filter(item => item.degree === 'BS');
        phds.sort((a, b) => Number(b.year) - Number(a.year));
        phds.forEach((item, index) => {
          if (index === 0 || index > 0 && years[index - 1] !== years[index]) {
            years.push(item.year);
          }
        });
        var phdWrapper = $('#lab-phd');
        for (var i = 0; i < years.length; i++) {
          var phdYear = $('<div class="phd-year border-bottom-line"></div>');
          var h2 = $('<h2></h2>').text(years[i]);
          var phdItem = $('<div class="phds"></div>');
          for (var j = 0; j < phds.length; j++) {
            if(phds[j].year === years[i]) {
              var span = $('<span class="phd-name"></span>').text(phds[j].studentname);
              phdItem.append(span);
            }
          }
          phdYear.append(h2).append(phdItem);
          phdWrapper.append(phdYear);
        }
      });
      break;
    }
    case 'ms': {
      initMain(5);
      var req = $.ajax({
        url: "http://39.106.171.39:8011/mbl/Student/getStudentList",
        method: "GET",
        data: {
          page: 1,
          pagesize: 12,
        },
        dataType: "json",
      });
      req.done(function (data) {
        // var facultyList = data.rows;
        var phds = data.rows || [];
        var years = [];
        phds = phds.filter(item => item.degree === 'MS');
        phds.sort((a, b) => Number(b.year) - Number(a.year));
        phds.forEach((item, index) => {
          if (index === 0 || index > 0 && years[index - 1] !== years[index]) {
            years.push(item.year);
          }
        });
        var phdWrapper = $('#lab-ms');
        for (var i = 0; i < years.length; i++) {
          var phdYear = $('<div class="phd-year border-bottom-line"></div>');
          var h2 = $('<h2></h2>').text(years[i]);
          var phdItem = $('<div class="phds"></div>');
          for (var j = 0; j < phds.length; j++) {
            if(phds[j].year === years[i]) {
              var span = $('<span class="phd-name"></span>').text(phds[j].studentname);
              phdItem.append(span);
            }
          }
          phdYear.append(h2).append(phdItem);
          phdWrapper.append(phdYear);
        }
      });
    }
  }
});
